const express = require('express');
const router = express.Router();
const rds = require('../rds');
const task = require('../task');

// 获取游戏状态的共享函数
async function getGameStatus(userId) {
    try {
        // 检查用户是否在trial_subjects中有记录
        const [[subject]] = await rds.query('SELECT * FROM trial_subjects WHERE user_id = ? AND trial_id = 1', [userId]);
        if (!subject) { return { success: false, message: '未找到用户记录' }; }

        // 获取研究助理二维码
        let assistantQR = '/apps/public/avatar-cc-300x300.jpg';
        const [[assistant]] = await rds.query('SELECT qr_code FROM trial_assistants WHERE is_active = 1 ORDER BY id DESC LIMIT 1');
        if (assistant) assistantQR = assistant.qr_code;

        // 确定当前应该显示的场景
        const subjectStatus = subject.status;
        const groupType = subject.group_type;
        const groupNo = subject.group_no || '--';

        // 场景一：上传知情同意书 (status < 2)
        const showConsent = subjectStatus < 2;

        // 场景二：添加研究助理 (status = 2)
        const showWelcome = subjectStatus === 2;

        // 场景三：主控台界面 (status >= 3)
        const showCockpit = subjectStatus >= 3;

        // 判断是否已经开始记录
        const hasStarted = subject.start_date && new Date(subject.start_date) < new Date();

        // 计算已完成天数
        let completedDays = 0;
        if (hasStarted) {
            const startDate = new Date(subject.start_date);
            const today = new Date();
            const diffTime = Math.abs(today - startDate);
            completedDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        }

        // 检查今天是否已有日记记录
        let hasTodayDiary = false;
        let totalDays = 0;

        if (hasStarted ) {
            // 检查今天是否已有日记记录
            const [todayDiaries] = await rds.query(
                `SELECT * FROM trial_diaries WHERE trial_id = ? AND subject_id = ?  AND DATE(diary_date) = CURDATE()`,
                [subject.trial_id, subject.id]
            );
            hasTodayDiary = todayDiaries.length > 0;

            // 获取所有日记记录
            const [diaries] = await rds.query(
                `SELECT DATE(diary_date) as diary_date 
                 FROM trial_diaries 
                 WHERE trial_id = ? AND subject_id = ?
                 AND diary_date >= ?`,
                [subject.trial_id, subject.id, subject.start_date || '1970-01-01']
            );
            totalDays = diaries.length;
        }

        const entry = JSON.parse(subject.entry_info);
        const hasSupplyAddress = entry && entry.recipient_address && entry.recipient_phone ? true: false;

        // 判断是否需要打卡
        const needCheckIn = hasStarted && !hasTodayDiary;

        // 判断是否有随访任务
        const followUpDays = [13, 27, 43, 57, 73, 87];
        let needFollowUp = false;
        //let followUps = []; // 准备随访列表
        if (hasStarted) {

            for (const day of followUpDays) {
                if (completedDays >= day) {
                    const isCompleted = await checkFollowUpCompleted(subject.id, day);
                    if (!isCompleted) {
                        needFollowUp = true;
                        break;
                    }
                }
            }

            /*
            followUps = await Promise.all(followUpDays.map(async (day) => {
                const followUpDate = new Date(subject.start_date);
                followUpDate.setDate(followUpDate.getDate() + day);
                return {
                    day: day,
                    date: followUpDate,
                    enabled: completedDays >= day,
                    completed: ( await checkFollowUpCompleted(subject.id, day))
                };
            }));
            */

        }

        // 获取已完成的随访记录
        const [followups] = await rds.query( `SELECT DISTINCT content FROM trial_follow_up WHERE subject_id = ?`, [subject.id]);

        // 计算已完成的随访数量
        const completedFollowUps = followups.reduce((count, followup) => {
            try {
                const content = JSON.parse(followup.content || '{}');
                return content.targetDay ? count + 1 : count;
            } catch (e) {
                return count;
            }
        }, 0);

        return {
            success: true,
            userId,
            assistantQR,
            showConsent,    //三选一
            showWelcome,    //三选一
            showCockpit,    //三选一
            needCheckIn,    //是否有日记需要写
            needFollowUp,   //是否有随访表需要填
            //followUps,      //截止目前的
            completedFollowUps, //截止目前已完成的随访记录
            totalDays,          //已完成日记总数
            startDate: subject.start_date,       //用于和当前日期比较
            subjectNo: subject.subject_no,
            groupType: subject.group_type,
            status: subject.status,
            finishTime: subject.finish_time,
            groupNo,
            isTrialGroup: subject.group_type === 1,
            isControlGroup: subject.group_type === 2,
            isViewerGroup: subject.group_type === 9,
            canLaunch:  (subject.group_type === 2 && hasSupplyAddress) || (subject.group_type === 1 && hasSupplyAddress) || (subject.group_type === 9)
        };
    } catch (error) {
        console.error('获取游戏状态失败:', error);
        return { success: false, message: '获取游戏状态失败', userId };
    }
}

// 渲染游戏页面
router.get('/game', async (req, res) => {
    const userId = req.session.totemUID;
    if (!userId) return res.status(401).send('用户未登录');

    try {
        // 检查用户是否在trial_subjects中有记录，如果没有则创建
        const [[subject]] = await rds.query( 'SELECT * FROM trial_subjects WHERE user_id = ? AND trial_id = 1', [userId]);
        if (!subject) {
            await rds.query( `INSERT INTO trial_subjects (trial_id, user_id, subject_no, status, group_type) VALUES (1, ?, ?, 0, 0)`, [userId, `BCH-${String(userId).padStart(6, '0')}`]);
        }

        // 使用共享函数获取游戏状态
        const status = await getGameStatus(userId);
        if (!status.success) return res.status(500).send(status.message);

        // 直接渲染状态数据
        res.render('space-journey/game', status);
    } catch (error) {
        console.error('渲染游戏页面失败:', error);
        res.status(500).send('服务器错误');
    }
});

// 上传知情同意书
router.post('/upload-consent', async (req, res) => {
    try {
        const userId = req.session.totemUID;
        const { consentFiles, name, gender, age, recipientName, recipientPhone, recipientAddress } = req.body;

        if (!consentFiles || !Array.isArray(JSON.parse(consentFiles)) || JSON.parse(consentFiles).length === 0) {
            return res.json({ success: false, message: '请上传知情同意书' });
        }

        if (!name || !gender || !age || !recipientName || !recipientPhone || !recipientAddress) {
            return res.json({ success: false, message: '请填写完整的信息' });
        }

        // 更新受试者记录
        await rds.query(
            `UPDATE trial_subjects SET status = 2, entry_info = ?, entry_time = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE user_id = ? AND trial_id = 1`,
            [JSON.stringify({ 
                consent_files: consentFiles, name, gender, age, recipient_name: recipientName,
                recipient_phone: recipientPhone, recipient_address: recipientAddress
            }), userId]
        );

        // 获取受试者记录ID
        const [[subject]] = await rds.query( 'SELECT * FROM trial_subjects WHERE user_id = ? AND trial_id = 1', [userId]);

        // 获取临床试验负责人ID
        const [[trial]] = await rds.query( 'SELECT principal_id FROM trials WHERE id = 1');

        if (trial && trial.principal_id) {
            // 向试验负责人发送提示任务
            const taskResult = await task.assignTask(
                "uid", // 任务发放对象的识别形式，固定值
                trial.principal_id, // 通知发放对象用户号，来自该临床试验负责人的principal_id
                "trial_entry_event", // 固定值
                `根据用户U#${userId}上传的入组通知书为其确认分组`, // 任务标题
                "Xiaoteng", // 固定值
                `https://totemlife.cn/apps/trial/admin/trials/1/subjects/${subject.id}`, // 任务链接
                `用户U#${userId}报到了试验#1: ${recipientName}, ${recipientAddress}, 受试人：${name}, ${gender}, ${age}岁`, // 任务描述
                "pending" // 任务状态
            );

            console.log('发送提示任务结果:', taskResult);
        }

        res.json({ success: true });
    } catch (error) {
        console.error('上传知情同意书失败:', error);
        res.json({
            success: false,
            message: '上传知情同意书失败'
        });
    }
});

// 获取游戏状态
router.get('/status', async (req, res) => {
    try {
        const userId = req.session.totemUID;
        if (!userId) {
            return res.json({ success: false, message: '用户未登录' });
        }

        // 使用共享函数获取游戏状态
        const status = await getGameStatus(userId);

        // 直接返回状态数据
        res.json(status);
    } catch (error) {
        console.error('获取游戏状态失败:', error);
        res.json({
            success: false,
            message: '获取游戏状态失败',
            userId
        });
    }
});

// 确认分组
router.post('/confirm-group', async (req, res) => {
    try {
        const userId = req.session.totemUID;
        // 检查用户是否已登记入组
        const [[subject]] = await rds.query( 'SELECT * FROM trial_subjects WHERE user_id = ? AND trial_id = 1', [userId]);

        if (!subject) {
            return res.json({ success: false, message: '尚未获得入组同意书，请联系项目助理' });
        }

        // 检查用户分组类型
        const groupType = subject.group_type;

        // 如果用户尚未被确认编组, 9是试验参观者
        if (groupType !== 1 && groupType !== 2 && groupType !== 9) {
            return res.json({ success: false, message: '你的试验还未确认编组，联系项目助理优先处理' });
        }

        // 检查用户是否在试验组 (group_type = 1) 或对照组 (group_type = 2) 或者是 观摩者 (group_type = 9)
        const isTrialGroup = groupType === 1;
        const isControlGroup = groupType === 2;
        const isViewerGroup = groupType === 9;

        res.json({ success: true, isTrialGroup, isControlGroup, isViewerGroup, });

    } catch (error) {
        console.error('确认分组失败:', error);
        res.json({ success: false, message: '确认分组失败' });
    }
});

// 检查随访是否已完成
async function checkFollowUpCompleted(subjectId, day) {
    try {
        // 查找该随访点的随访记录，使用content中的targetDay字段
        const [followups] = await rds.query(
            `SELECT * FROM trial_follow_up WHERE subject_id = ? AND content LIKE ?  ORDER BY created_at DESC LIMIT 1`, [subjectId, `%"targetDay":${day}%`]
        );
        return followups.length > 0;
    } catch (error) {
        console.error('检查随访完成状态失败:', error);
        return false;
    }
}

// 设置开始日期
router.post('/start', async (req, res) => {
    try {
        const uid = req.session.totemUID;
        if (!uid) { return res.json({ success: false, message: '用户未登录' }); }

        const { startDate } = req.body;
        if (!startDate) { return res.json({ success: false, message: '开始日期不能为空' }); }

        // 检查是否已经设置过开始日期
        const [[subject]] = await rds.query( 'SELECT * FROM trial_subjects WHERE user_id = ? and trial_id = 1', [uid]);
        if (subject && subject.start_date) { return res.json({ success: false, message: '已经设置过开始日期' }); }

        await rds.query(
            'UPDATE trial_subjects SET start_date = ?, updated_at = NOW() WHERE user_id = ? and trial_id = 1',
            [startDate, uid]
        );

        res.json({ success: true });
    } catch (error) {
        console.error('Error setting start date:', error);
        res.json({ success: false, message: '设置开始日期失败' });
    }
});

// 结束旅程
router.post('/exit', async (req, res) => {
    try {
        const uid = req.session.totemUID;
        if (!uid) { return res.json({ success: false, message: '用户未登录' }); }

        // 检查是否已经开始旅程
        const [[subject]] = await rds.query( 'SELECT * FROM trial_subjects WHERE user_id = ? and trial_id = 1', [uid]);
        if (!subject || !subject.start_date) {
            return res.json({ success: false, message: '尚未开始旅程' });
        }

        // 结束旅程-待实现
        res.json({ success: true, message: '尚不能自助退出，请联系导航员' });

    } catch (error) {
        console.error('Error exiting subject:', error);
        res.json({ success: false, message: '结束旅程失败' });
    }
});

// 获取今日航程日记
router.get('/diaries/today', async (req, res) => {
    try {
        const userId = req.session.totemUID;

        // 先获取用户的trial_id和subject_id
        const [[subject]] = await rds.query(
            `SELECT s.id as subject_id, s.trial_id FROM trial_subjects s WHERE s.user_id = ? and s.trial_id = 1`,
            [userId]
        );

        if (!subject) {
            throw new Error('未找到您的试验信息');
        }

        // 使用trial_id和subject_id查询今日日记
        const [diaries] = await rds.query(
            `SELECT * FROM trial_diaries 
             WHERE trial_id = ? AND subject_id = ? 
             AND DATE(diary_date) = CURDATE()
             LIMIT 1`,
            [subject.trial_id, subject.subject_id]
        );

        res.json({ 
            success: true, 
            diary: diaries[0] ? {
                ...diaries[0],
                content: JSON.parse(diaries[0].content || '{}')
            } : null
        });
    } catch (error) {
        console.error('获取今日航程日记失败:', error);
        res.json({ success: false, message: error.message || '获取今日航程日记失败' });
    }
});

// 获取航程日记历史（移除原有的/diaries接口，只保留分页的历史记录接口）
router.get('/diaries/history', async (req, res) => {
    try {
        const userId = req.session.totemUID;
        const page = parseInt(req.query.page) || 1;
        const pageSize = parseInt(req.query.pageSize) || 5;

        // 先获取用户的trial_id和subject_id
        const [[subject]] = await rds.query( `SELECT s.id as subject_id, s.trial_id FROM trial_subjects s WHERE s.user_id = ? and s.trial_id = 1`, [userId]
        );

        if (!subject) {
            throw new Error('未找到您的试验信息');
        }

        // 获取总记录数
        const [[{ total }]] = await rds.query(
            `SELECT COUNT(*) as total FROM trial_diaries 
             WHERE trial_id = ? AND subject_id = ? 
             AND diary_date < CURDATE()`,
            [subject.trial_id, subject.subject_id]
        );

        // 使用trial_id和subject_id查询历史日记，带分页
        const [diaries] = await rds.query(
            `SELECT * FROM trial_diaries 
             WHERE trial_id = ? AND subject_id = ? 
             AND diary_date < CURDATE() 
             ORDER BY diary_date DESC
             LIMIT ${parseInt(pageSize)} OFFSET ${parseInt((page - 1) * pageSize)}`,
            [
                parseInt(subject.trial_id),
                parseInt(subject.subject_id)
            ]
        );

        res.json({ 
            success: true, 
            diaries: diaries.map(diary => ({
                ...diary,
                content: JSON.parse(diary.content || '{}')
            })),
            pagination: {
                total,
                page,
                pageSize,
                hasMore: total > page * pageSize
            }
        });
    } catch (error) {
        console.error('获取历史航程日记失败:', error);
        res.json({ success: false, message: error.message || '获取历史航程日记失败' });
    }
});

// 保存航程日记
router.post('/diary', async (req, res) => {
    try {
        const userId = req.session.totemUID;
        const content = req.body;

        // 先获取用户的trial_id和subject_id
        const [[subject]] = await rds.query( `SELECT s.id as subject_id, s.trial_id FROM trial_subjects s WHERE s.user_id = ? and s.trial_id = 1`, [userId]);

        if (!subject) {
            throw new Error('未找到您的试验信息');
        }

        // 检查今天是否已经有日记
        const [[existingDiary]] = await rds.query(
            `SELECT id FROM trial_diaries 
             WHERE trial_id = ? AND subject_id = ? 
             AND diary_date = CURDATE()`,
            [subject.trial_id, subject.subject_id]
        );

        if (existingDiary) {
            // 更新今天的日记
            await rds.query(
                `UPDATE trial_diaries 
                 SET content = ? 
                 WHERE id = ?`,
                [JSON.stringify(content), existingDiary.id]
            );
        } else {
            // 创建新的日记
            await rds.query(
                `INSERT INTO trial_diaries 
                 (trial_id, subject_id, diary_date, content) 
                 VALUES (?, ?, CURDATE(), ?)`,
                [subject.trial_id, subject.subject_id, JSON.stringify(content)]
            );
        }

        res.json({ success: true, message: '航程日记保存成功' });
    } catch (error) {
        console.error('保存航程日记失败:', error);
        res.json({ success: false, message: error.message || '保存航程日记失败' });
    }
});

// 定期随访
router.post('/followup', async (req, res) => {
    try {
        const uid = req.session.totemUID;
        if (!uid) {
            return res.json({ success: false, message: '用户未登录' });
        }

        const { targetDay, followupContent } = req.body;
        if (!targetDay || !followupContent) {
            return res.json({ success: false, message: '随访信息不完整' });
        }

        // 获取受试者ID和试验ID
        const [[subject]] = await rds.query( 'SELECT * FROM trial_subjects WHERE user_id = ? AND trial_id = 1', [uid]);

        if (!subject) {
            return res.json({ success: false, message: '未找到受试者记录' });
        }

        // 计算当前是第几天
        const startDate = new Date(subject.start_date);
        const today = new Date();
        const actualDay = Math.ceil((today - startDate) / (1000 * 60 * 60 * 24));

        // 解析前端传来的JSON内容，确保包含targetDay
        let content;
        try {
            content = JSON.parse(followupContent);
            content.targetDay = parseInt(targetDay);
        } catch (e) {
            // 如果解析失败，则使用原始内容
            content = { targetDay: parseInt(targetDay), content: followupContent };
        }

        // 检查是否已经提交过该目标随访点的随访
        const [existingFollowups] = await rds.query(
            `SELECT * FROM trial_follow_up WHERE subject_id = ? AND content LIKE ?  ORDER BY id DESC LIMIT 1`, [subject.id, `%"targetDay":${targetDay}%`]
        );

        if (existingFollowups.length > 0) {
            // 更新随访记录
            await rds.query(
                'UPDATE trial_follow_up SET content = ?, updated_at = NOW() WHERE id = ?', [JSON.stringify(content), existingFollowups[0].id]
            );
        } else {
            // 创建新随访记录，使用实际天数作为day字段
            await rds.query(
                'INSERT INTO trial_follow_up (trial_id, subject_id, day, content, created_at, updated_at) VALUES (?, ?, ?, ?, NOW(), NOW())',
                [subject.trial_id, subject.id, actualDay, JSON.stringify(content)]
            );
        }

        res.json({ success: true });
    } catch (error) {
        console.error('Error submitting followup:', error);
        res.json({ success: false, message: '提交随访记录失败' });
    }
});

// 获取随访记录
router.get('/followups', async (req, res) => {
    try {
        const uid = req.session.totemUID;
        if (!uid) { return res.json({ success: false, message: '用户未登录' }); }

        // 获取受试者ID
        const [[subject]] = await rds.query( 'SELECT * FROM trial_subjects WHERE user_id = ? AND trial_id = 1', [uid]);

        if (!subject) { return res.json({ success: false, message: '未找到受试者记录' }); }

        // 获取所有随访记录
        const [followups] = await rds.query( 'SELECT * FROM trial_follow_up WHERE subject_id = ? ORDER BY created_at ASC', [subject.id]);

        const startDate = subject?.start_date ? new Date(subject.start_date) : null;

        // 定义预期的随访天数
        const followUpDays = [13, 27, 43, 57, 73, 87];

        // 组织随访记录，按照targetDay分组
        const organizedFollowups = [];

        followups.forEach(followup => {
            // 解析JSON内容
            let content;
            try {
                content = JSON.parse(followup.content || '{}');
            } catch (e) {
                content = { targetDay: followup.day };
            }

            const targetDay = content.targetDay || followup.day;

            // 查找是否已经有该targetDay的记录
            const existingIndex = organizedFollowups.findIndex(f => f.targetDay === targetDay);

            if (existingIndex >= 0) {
                // 如果已有记录，且当前记录更新，则替换
                if (new Date(followup.created_at) > new Date(organizedFollowups[existingIndex].createdAt)) {
                    organizedFollowups[existingIndex] = {
                        id: followup.id, day: followup.day, targetDay: targetDay,
                        date: startDate ? new Date(startDate.getTime() + (followup.day - 1) * 24 * 60 * 60 * 1000) : null,
                        targetDate: startDate ? new Date(startDate.getTime() + (targetDay - 1) * 24 * 60 * 60 * 1000) : null,
                        content: content, createdAt: followup.created_at, updatedAt: followup.updated_at
                    };
                }
            } else {
                // 如果没有该targetDay的记录，则添加
                organizedFollowups.push({
                    id: followup.id, day: followup.day, targetDay: targetDay,
                    date: startDate ? new Date(startDate.getTime() + (followup.day - 1) * 24 * 60 * 60 * 1000) : null,
                    targetDate: startDate ? new Date(startDate.getTime() + (targetDay - 1) * 24 * 60 * 60 * 1000) : null,
                    content: content, createdAt: followup.created_at, updatedAt: followup.updated_at
                });
            }
        });

        // 计算当前天数
        const currentDay = startDate ? Math.ceil((new Date() - startDate) / (1000 * 60 * 60 * 24)) : 0;

        // 添加未完成的随访点
        followUpDays.forEach(day => {
            // 只添加已经到达或过去的随访点
            if (currentDay >= day && !organizedFollowups.some(f => f.targetDay === day)) {
                organizedFollowups.push({
                    id: null, day: null, targetDay: day, date: null,
                    targetDate: startDate ? new Date(startDate.getTime() + (day - 1) * 24 * 60 * 60 * 1000) : null,
                    content: null, createdAt: null, updatedAt: null, completed: false
                });
            } else if (organizedFollowups.some(f => f.targetDay === day)) {
                // 标记已完成的随访点
                const index = organizedFollowups.findIndex(f => f.targetDay === day);
                if (index >= 0) {
                    organizedFollowups[index].completed = true;
                }
            }
        });

        // 按targetDay排序
        organizedFollowups.sort((a, b) => a.targetDay - b.targetDay);

        res.json({ success: true, startDate: startDate, currentDay: currentDay, followups: organizedFollowups });
    } catch (error) {
        console.error('Error getting followups:', error);
        res.json({ success: false, message: '获取随访记录失败' });
    }
});

// 获取待完成的随访任务
router.get('/pending-followups', async (req, res) => {
    try {
        const uid = req.session.totemUID;
        if (!uid) {
            return res.json({ success: false, message: '用户未登录' });
        }

        // 获取受试者ID
        const [[subject]] = await rds.query( 'SELECT * FROM trial_subjects WHERE user_id = ? AND trial_id = 1', [uid]);

        if (!subject) {
            return res.json({ success: false, message: '未找到受试者记录' });
        }

        if ( !subject.start_date) {
            return res.json({ success: true, pendingFollowups: [] });
        }

        const startDate = new Date(subject.start_date);
        const today = new Date();
        const currentDay = Math.ceil((today - startDate) / (1000 * 60 * 60 * 24));

        // 定义预期的随访天数
        const followUpDays = [13, 27, 43, 57, 73, 87];

        // 获取已完成的随访记录
        const [completedFollowups] = await rds.query( `SELECT * FROM trial_follow_up WHERE subject_id = ?`, [subject.id]);

        // 提取已完成的随访点
        const completedDays = new Set();
        completedFollowups.forEach(followup => {
            try {
                const content = JSON.parse(followup.content || '{}');
                if (content.targetDay) {
                    completedDays.add(parseInt(content.targetDay));
                }
            } catch (e) {
                // 忽略解析错误
            }
        });

        // 找出待完成的随访点
        const pendingFollowups = followUpDays
            .filter(day => currentDay >= day && !completedDays.has(day))
            .map(day => ({
                day,
                date: new Date(startDate.getTime() + (day - 1) * 24 * 60 * 60 * 1000),
                daysOverdue: currentDay - day
            }));

        res.json({ success: true, currentDay, pendingFollowups });

    } catch (error) {
        console.error('Error getting pending followups:', error);
        res.json({ success: false, message: '获取待完成随访任务失败' });
    }
});

module.exports = router; 
